import Common from '@/utils/Common.js';

var FileUtil = {};

FileUtil.save = (dirName, fileName, blob) => {
	let dirPath = Common.directory().base + dirName;
	let promise = new Promise((resolve, reject) => {
		window.resolveLocalFileSystemURL(dirPath, dirEntry => {
			dirEntry.getFile(fileName, {create: true, exclusive: false}, fileEntry => {
				 fileEntry.createWriter(fileWriter => {
					 let filePath = dirPath + "/" + fileName;
					 fileWriter.onwriteend = function() {
                         console.log("wirte file finish: " + filePath);
                         resolve(filePath);
                     };
                     fileWriter.onerror = function(error) {
                         console.error(error);
                         reject(error);
                     };
					 fileWriter.write(blob);
				 }, error => {
					console.error(error);
					reject(error);
				});
			}, error => {
				console.error(error);
				reject(error);
			});
		}, error => {
			console.error(error);
			reject(error);
		})
	});
	return promise;
}

FileUtil.read = (filePath, type) => {
	let promise = new Promise((resolve, reject) => {
		window.resolveLocalFileSystemURL(filePath, fileEntry => {
			fileEntry.file(file => {
				var reader = new FileReader();
	            reader.onloadend = function () {
	                let blob = new Blob([this.result], {type});
	                resolve(blob);
	            };
	            reader.readAsArrayBuffer(file);
			}, error => {
				console.error(error);
				reject(error);
			});
		}, error => {
			console.error(error);
			reject(error);
		})
	});
	return promise;
}

FileUtil.remove = (filePath) => {
	let promise = new Promise((resolve, reject) => {
		window.resolveLocalFileSystemURL(filePath, fileEntry => {
			fileEntry.remove();
			resolve(filePath);
		}, error => {
			console.error(error);
			reject(error);
		});
	});
	return promise;
}

FileUtil.copy = (from, to) => {
	let promise = new Promise((resolve, reject) => {
		let fileTransfer = new FileTransfer();
		fileTransfer.download(from, to, fileEntry => {
			resolve(to);
		}, error => {
			console.error(error);
			reject(error);
		})
	});
	return promise;
}

export default FileUtil;